package com.znyj.servlet.utilsTool;

import com.znyj.servlet.constant.SysConstant;
import com.znyj.servlet.entity.ScheduledEntity;
import com.znyj.servlet.service.FactoryService;
import com.znyj.servlet.service.ScheduledService;
import com.znyj.servlet.task.ScheduledTaskMapping;
import com.znyj.servlet.task.model.ScheduledTaskModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Created by gaoliwei02 on 17/7/5.
 */
@Component
public class InitComponent implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(InitComponent.class);

    @Resource
    private FactoryService factoryService;

    @Resource
    private ScheduledService scheduledService;

    @Resource
    private ScheduledTaskMapping scheduledTaskMapping;

    @Override
    public void afterPropertiesSet() throws Exception {
        final Properties properties = new Properties();
        final InputStream stream = CommonTool.class.getClassLoader().getResourceAsStream("system.properties");
        try {
            properties.load(stream);
            SysConstant.THRIFT_ADDR = properties.getProperty("system.thrift.addr");
            SysConstant.SESSION_TIMEOUT = Integer.parseInt(properties.getProperty("system.session.overtime"));
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yy");
        Date date = new Date();
        String formatDate = sdf.format(date);

        Calendar c = Calendar.getInstance();
        String week = String.valueOf(c.get(Calendar.WEEK_OF_YEAR));

        String exp = "^[0-9]{3}" + formatDate + week + "[0-9]{5}$";
        int count = factoryService.countByExp(exp);
        logger.info("init exp: " + exp + "/init count: " + count);
        CommonTool.swapSequenceId(count);
        logger.info("sequenceId: " + CommonTool.getSequenceId());
        DesUtil.init();

        //把关闭任务继续
        List<ScheduledEntity> scheduledEntityList = scheduledService.initScheduled();
        for (int i = 0; i < scheduledEntityList.size(); i++) {
            if (scheduledEntityList.get(i).getExecuteResult().equals("")) {
                logger.info("last scheduled task:{}" + scheduledEntityList.get(i).toString());
                ScheduledTaskModel scheduledTaskModel = new ScheduledTaskModel(scheduledEntityList.get(i));
                scheduledTaskMapping.add(scheduledTaskModel.scheduledEntity.getOpenOrderId(), scheduledTaskModel);
            }
        }
    }
}
